<?php
class MessagesController extends AppController {

	var $name = 'Messages';
	var $uses = array('Message', 'Intercept');
	
	var $cp = null;		//curl pointer
	var $httpResponseOnError = array(4, 5);	//http response code's first number on errors
	var $httpResponseOnRedirect = 3;		//http response code on redirect
	var $errorz = array();		//array for storing errorz
	//var $allowedChars = array(' ', '@', ':', '/', '!', '?', '.');		//paranoid sanitize esetén kell egyenlőre hagyjuk html-ként

	function isAuthorized(){
		if($this->Auth->user('group_id') == $this->Session->read('Settings.adminPermission')){		//admin jogosultságú júzerek
			return true;
		}
		//free user / premium user / business user
		if(in_array($this->action, array(
													'index',
													'send'
													))){
			return true;
		}
		return false;		//minden más tiltva
	}

/*
 * Get last 5 sent messages from all of the registered accounts
*/		
	function index(){
		$this->Message->unbindModel(array('belongsTo' => array('User')));
		$this->Message->Account->unbindModel(array('belongsTo' => array('User')));
		$messages = $this->Message->find('all',
													  array(
															'conditions' => array('user_id' => $this->Auth->user('id')),
															'order' => array('Message.created DESC'),
															'limit' => 5,
															'recursive' => 2	//igen, ez kell nekünk
															)
													  );
		
		$this->Message->Account->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Intercept')));
		$accounts = $this->Message->Account->find('all',
											  array(
												'fields' => array('Account.id', 'Account.username', 'Account.extras', 'Community.name'),
												'conditions' => array('user_id' => $this->Auth->user('id'))
												));
		
		if(count($accounts)){
			$this->set('accounts', $accounts);
			
			$accountIds = array();
			foreach($accounts as $a){
				$accountIds[] = $a['Account']['id'];
			}
			//get intercepts on startup also not just messages
			/*$intercepts = $this->Intercept->find('all',
																 array(
																	'conditions' => array('account_id' => $accountIds),
																	'order' => 'created DESC',
																	'limit' => 20
																 )
															 );
			foreach($intercepts as $index => $ics){
				$intercepts[$index]['Message'] = $intercepts[$index]['Intercept'];
			}
			$messages = array_merge($messages, $intercepts);
			debug($messages);*/
			$this->set('messages', $messages);
		}
		else	//if there is no account we should redirect the user for create them
			$this->redirect(array('controller' => 'users', 'action' => 'edit'));
	}

/*
 * Sends messages to the sociall networks
*/
	function send(){
		if($this->data){
			$isAjax = $this->RequestHandler->isAjax();
			
			$unfilteredMessage = $this->data['Message']['message'] ? $this->data['Message']['message'] : null;
			App::import('Sanitize');

			$this->data['Message']['message'] = Sanitize::html($this->data['Message']['message']);
			if($this->Session->read('ping'))
				$this->Session->delete('ping');

			$this->_curlInit();

			//is there message?
			if(!$this->data['Message']['message']){
				if($isAjax){
					$this->set('error', __('There is no message. How could I send it, baby?', true));
					$this->render();
				}
				else{
					$this->Session->setFlash(__('There is no message. How could I send it, baby?', true));
					$this->redirect('/');
				}
			}
			//at least 1 account supposed to be checked
			$c = 0;
			foreach($this->data['Account'] as $key => $value){
				if($value){
					$c += $value;
					$this->data['Account']['Account'][] = $value;
				}
				unset($this->data['Account'][$key]);
			}
			
			if(!$c){
				if($isAjax){
					$this->set('error', __('You should check at least one account to send the message.', true));
					$this->render();
				}
				else{
					$this->Session->setFlash(__('You should check at least one account to send the message.', true));
					$this->redirect('/');
				}
			}
			
			//it looks ok let's save & send the messages
			//save the messages to the database
			$this->data['Message']['user_id'] = $this->Auth->user('id');
			//debug($this->data);
			/*
			Array(
				[Message] => Array(
					[id] => 
					[user_id] => 1
					[message] => 123)
				[Account] => Array(
					[Account] => Array(
                    [0] => 1
                    [1] => 18
                    [2] => 19
                )))
			*/
			if(!$this->Message->save($this->data)){
				if($isAjax){
					$this->set('error', __('The messages is not saved and did not send anywhere.', true));
					$this->render();					
				}
				else{
					$this->Session->setFlash(__('The messages is not saved and did not send anywhere.', true));
					$this->redirect('/');
				}
			}
			else{
				$sentMessages = array('created'	=> date('Y-m-d H:i:s'));
				foreach($this->data['Account']['Account'] as $value){
					//we need username and pass for the account
					$account = $this->Message->Account->find('first', array(
															'fields' => array(
																				'Account.id',
																				'Account.username',
																				'Account.pass',
																				'Account.extras', 
																				'Community.name'
																				),
															'conditions' => array(
																					'User.id' => $this->Auth->user('id'),	//account id came by post so it is better to recheck if it belongs to this user
																					'Account.id' => $value
																					)
															));
					//debug($account);					
					$success = $this->_sendMessage($account, $unfilteredMessage);
					if($success)
						$sentMessages['details'][] = array(
											'username' => $account['Account']['username'],
											'community' => $account['Community']['name']
											);
/*
{"created":"2009-10-08 12.30:18",
"details":[{"username":"rrd108@gmail.com","community":"iwiw"},
	{"username":null,"community":null},
	{"username":null,"community":null}]}
	
	elküldi de a timelinon nem jól jeleníti meg
*/
					else{
						//sending was unsucessfull we should update the accounts_messages table data
						$idWithError = $this->Message->AccountsMessage->field('id', array(
																								'message_id' => $this->Message->id,
																								'account_id' => $value
																								)
																						);
						$this->Message->AccountsMessage->id = $idWithError;
						$this->Message->AccountsMessage->saveField('error', true);
						$sentMessages['details'][] = array(
											'username' => $account['Account']['username'],
											'community' => $account['Community']['name'],
											'extra' => 'error'
											);
					}
				}
			}
		$this->set('sentMessages', $sentMessages);
		$this->set('errorz', $this->errorz);
		//if(count($this->errorz))
			$this->log('send messages: ' . print_r($this->errorz, true), LOG_DEBUG);
		$this->_curlFinish();
		if(!$isAjax)
			$this->redirect('/');
		}
	}
	
/*
 * Get curl errors
 * @param array $account account username and password
 * @param string $message message from the server or generated by ourselves
 * @return false if no error or array on error
*/
	function _getCurlError($account, $message = null){
		$responseCode = curl_getinfo($this->cp, CURLINFO_HTTP_CODE);
		if(in_array(substr($responseCode, 0, 1), $this->httpResponseOnError)){
			//we have an error
			return(
				array(
					'type' => 'curlError',
					'data' => array(
									'account' => $account,
									'responseCode' => $responseCode,
									'message' => $message
									)
						)
				);
		}
		else
			return false;
	}

/*
 * Give the message to the sub functions to send it
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @param string $message the message to send
 * @access private
 * @permission user level
 * @return bool true on success
*/	
	function _sendMessage($account, $message){
		$message = urlencode($message);
		
		if($account['Community']['name'] == 'iwiw'){
			$success = $this->_sendMessageByIwiw($account, $message);
		}
		if($account['Community']['name'] == 'twitter'){
			$success = $this->_sendMessageByTwitter($account, $message);
		}
		if($account['Community']['name'] == 'facebook'){
			$success = $this->_sendMessageByFacebook($account, $message);
		}
		//debug($success);
		$curlError = $this->_getCurlError($account, $success);
		//debug($curlError);
		if($curlError){
			//we have an error
			array_push($this->errorz, $curlError);
			return false;
		}
		elseif($success)
			return true;
		else
			return false;
	}
	
/*
 * Sends the message to twitter
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @param string $message the message to send
 * @access private
 * @permission user level
 * @return bool true on success
*/		
	function _sendMessageByTwitter($account, $message){
		//debug($account);
		App::import('Vendor', 'twitterOAuth', array('file' => 'twitterOAuth.php'));
		$secrets = unserialize($account['Account']['extras']);
		$secrets = array(
							'oauth_token' => $this->_decodePass($secrets['oauth_token']),
							'oauth_token_secret' => $this->_decodePass($secrets['oauth_token_secret'])
							);

		$twitterOAuth = new TwitterOAuth(
										$this->Option->field('value', array('name' => 'twitter_consumer_key')),
										$this->Option->field('value', array('name' => 'twitter_secret_key')),
										$secrets['oauth_token'],
										$secrets['oauth_token_secret']);

		$url = 'https://twitter.com/statuses/update.json';
		$postData = array('status' => urldecode($message));
		$request = $twitterOAuth->post($url,$postData);
		if(isset($request->error)){
			array_push($this->errorz, $request->request . ' :: ' . $request->error);
			return false;
		}
		return $request;
	}

/*
 * Sends the message to facebook
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @param string $message the message to send
 * @access private
 * @permission user level
 * @return bool true on success
*/
	function _sendMessageByFacebook($account, $message){
		App::import('Vendor', 'facebook');
		$app_id = $this->Option->field('value', array('name' => 'facebook_app_id'));
		$api_key = $this->Option->field('value', array('name' => 'facebook_api_key'));
		$secret = $this->Option->field('value', array('name' => 'facebook_secret_key'));
		
		$facebook = new Facebook($api_key, $secret);
		//$user = $facebook->require_login();
		$user = unserialize($account['Account']['extras']);
		$facebook->set_user($user['userId'], $account['Account']['pass']);
		try{
			$success = $facebook->api_client->stream_publish(urldecode($message));
			//$success = $facebook->api_client->stream_publish(urldecode($message), null, null, null, '55725547663');
		}
		catch(Exception $e){
			$facebookError = array(
										'type' => 'facebookError',
										'data' => array(
														'time' => date('>-m-d H:i:s'),
														'account' => $account['Account']['id'],
														'message' => $e->getMessage()
														)
										);
			array_push($this->errorz, $facebookError);
			//debug($e->getMessage());
			return false;
		}
		//debug($success);
		return $success;
	}

/*
 * Sends the message to iwiw
 * @param array $account all neccesarry information to log in to the given social network
 * 		[Account] => Array(
 *            [username] => rrd108@gmail.com
 *            [pass] => YWRuaXZvZzQ1Mytqc2RsYSVmam89RlNpZyFpbTlDYWdGMEcyUmludkQ=)
 *         [Community] => Array(
 *            [name] => iwiw)
 * @param string $message the message to send
 * @access private
 * @permission user level
 * @return bool true on success
*/	
	function _sendMessageByIwiw($account, $message){
		App::import('Vendor', 'iwiw');
		$iwiwSid = $this->Session->read('iwiwSid.acc_'.$account['Account']['id']);
		$iwiw = new Iwiw($iwiwSid);
		$iwiwLogin = $account['Account'];
		$iwiwLogin['pass'] = $this->_decodePass($iwiwLogin['pass']);
		//debug($iwiwLogin);
		$iwiwSid = $iwiw->login($iwiwLogin);
		//debug($iwiwSid);
		if(isset($iwiwSid['error']))
			return false;
		$this->Session->write('iwiwSid.acc_'.$account['Account']['id'], $iwiwSid);
		$success = $iwiw->sendMessage($message);
		//debug($succes);
		if(isset($success['error'])){
			array_push($this->errorz, array(
									'type' => 'iwiwError',
									'data' => array(
														'account' => $account,
														'responseCode' => null,
														'message' => __('Iwiw connection error', true),
														'extra' => $success['error']
														)
									));
			return false;
		}
		else
			return true;
	}

}
?>
